<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="退货单号" prop="returnCode">
        <el-input v-model="queryParams.returnCode" placeholder="请输入退货单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <el-select v-model="queryParams.supplierId" placeholder="请选择供应商" clearable>
          <el-option v-for="supplier in supplierList" :key="supplier.supplierId" :label="supplier.supplierName"
            :value="supplier.supplierId" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="待退货" value="0" />
          <el-option label="已退货" value="1" />
          <el-option label="已取消" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <!-- 新增查询条件 -->
      <el-form-item label="仓库" prop="warehouseId">
        <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库" clearable>
          <el-option v-for="warehouse in warehouseList" :key="warehouse.warehouseId" 
            :label="warehouse.warehouseName" :value="warehouse.warehouseId" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="退货类型" prop="returnType">
        <el-select v-model="queryParams.returnType" placeholder="请选择退货类型" clearable>
          <el-option label="质量问题" value="QUALITY" />
          <el-option label="数量过多" value="EXCESS" />
          <el-option label="损坏" value="DAMAGE" />
          <el-option label="其他" value="OTHER" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="原入库单" prop="originalReceiptId">
        <el-input v-model="queryParams.originalReceiptId" placeholder="请输入原入库单ID" clearable />
      </el-form-item>
      
      <el-form-item label="退货日期">
        <el-date-picker v-model="dateRange" type="daterange" 
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
          value-format="yyyy-MM-dd" @change="handleDateRangeChange" />
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['mes:purchase:return:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['mes:purchase:return:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mes:purchase:return:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-check" size="mini" :disabled="single" @click="handleAudit"
          v-hasPermi="['mes:purchase:return:audit']">审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-s-operation" size="mini" :disabled="single" @click="handleExecute"
          v-hasPermi="['mes:purchase:return:execute']">执行退货</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['mes:purchase:return:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="returnList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="退货单ID" align="center" prop="returnId" />
      <el-table-column label="退货单号" align="center" prop="returnCode" />
      <el-table-column label="供应商" align="center" prop="supplierName" />
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="退货人" align="center" prop="returnBy" />
      <el-table-column label="退货时间" align="center" prop="returnTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_return_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- 新增显示列 -->
      <el-table-column label="原入库单号" align="center" prop="originalReceiptCode" />
      <el-table-column label="退货类型" align="center" prop="returnType">
        <template slot-scope="scope">
          <el-tag :type="getReturnTypeTagType(scope.row.returnType)">{{ getReturnTypeText(scope.row.returnType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="退货总金额" align="center" prop="totalAmount" />
      <el-table-column label="退货总数量" align="center" prop="totalQuantity" />
      <el-table-column label="审核人" align="center" prop="approvedBy" />
      <el-table-column label="审核时间" align="center" prop="approvedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approvedTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:purchase:return:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['mes:purchase:return:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改退货单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="退货单号" prop="returnCode">
              <el-input v-model="form.returnCode" placeholder="请输入退货单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="form.supplierId" placeholder="请选择供应商" @change="handleSupplierChange">
                <el-option v-for="supplier in supplierList" :key="supplier.supplierId" :label="supplier.supplierName"
                  :value="supplier.supplierId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="请选择仓库">
                <el-option v-for="warehouse in warehouseList" :key="warehouse.warehouseId"
                  :label="warehouse.warehouseName" :value="warehouse.warehouseId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退货人" prop="returnBy">
              <el-select v-model="form.returnBy" placeholder="请选择退货人">
                <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.nickName" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="退货时间" prop="returnTime">
              <el-date-picker v-model="form.returnTime" type="date" placeholder="选择退货时间" value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 退货明细 -->
        <el-divider content-position="left">退货明细</el-divider>
        <el-row>
          <el-col :span="24">
            <el-button type="primary" size="mini" @click="addReturnItem">添加明细</el-button>
          </el-col>
        </el-row>
        <el-table :data="form.returnItemList" style="width: 100%; margin-top: 10px;">
          // 在明细表格中
          <el-table-column label="物料" prop="materialName" width="200">
            <template slot-scope="scope">
              <el-select v-model="scope.row.materialId" placeholder="请选择物料"
                @change="handleMaterialChange(scope.$index)">
                <el-option v-for="material in materialList" :key="material.materialId" :label="material.materialName"
                  :value="material.materialId" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" prop="specification" width="150" />
          <el-table-column label="单位" prop="unitOfMeasure" width="80" />
          <el-table-column label="退货数量" prop="quantity" width="120">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.quantity" :min="0" :precision="2"
                @change="calculateAmount(scope.$index)" />
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="unitPrice" width="120">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.unitPrice" :min="0" :precision="2"
                @change="calculateAmount(scope.$index)" />
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="amount" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.amount || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="批次号" prop="batchNumber" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.batchNumber" placeholder="请输入批次号" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete"
                @click="removeReturnItem(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  listReturn, getReturn, delReturn, addReturn, updateReturn, 
  approveReturn, executeReturn, listCompletedReturn,
  listReturnByReceiptId, listReturnBySupplierId, 
  listReturnByWarehouseId, listReturnByType 
} from "@/api/mes/purchase/return";
import { listMaterial } from "@/api/mes/basic/material";
import { listWarehouse } from "@/api/mes/inventory/warehouse";
import { listUser } from "@/api/system/user";
import { listSupplier } from "@/api/mes/basic/supplier";

export default {
  name: "Return",
  dicts: ['mes_return_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 退货单表格数据
      returnList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        returnCode: null,
        supplierId: null,
        warehouseId: null,
        returnType: null,
        originalReceiptId: null,
        status: null,
        startDate: null,
        endDate: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        returnCode: [
          { required: true, message: "退货单号不能为空", trigger: "blur" }
        ],
        supplierId: [
          { required: true, message: "供应商不能为空", trigger: "change" }
        ],
        warehouseId: [
          { required: true, message: "仓库不能为空", trigger: "change" }
        ],
        returnBy: [
          { required: true, message: "退货人不能为空", trigger: "change" }
        ],
        returnTime: [
          { required: true, message: "退货时间不能为空", trigger: "blur" }
        ]
      },
      // 供应商列表
      supplierList: [
        { supplierId: 1, supplierName: "供应商A" },
        { supplierId: 2, supplierName: "供应商B" }
      ],
      // 仓库列表
      warehouseList: [],
      // 物料列表
      materialList: [],
      // 用户列表
      userList: []
    };
  },
  created() {
    this.getList();
    this.getWarehouseList();
    this.getMaterialList();
    this.getUserList();
    this.getSupplierList(); // 添加这行
  },
  methods: {
    /** 查询退货单列表 */
    getList() {
      this.loading = true;
      listReturn(this.queryParams).then(response => {
        this.returnList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取仓库列表 */
    getWarehouseList() {
      listWarehouse().then(response => {
        this.warehouseList = response.rows;
      });
    },
    /** 获取物料列表 */
    getMaterialList() {
      listMaterial().then(response => {
        this.materialList = response.rows;
      });
    },
    /** 获取用户列表 */
    getUserList() {
      listUser().then(response => {
        this.userList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        returnId: null,
        returnCode: null,
        supplierId: null,
        warehouseId: null,
        returnBy: null,
        returnTime: null,
        status: "0",
        remark: null,
        returnItemList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.returnId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加退货单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const returnId = row.returnId || this.ids
      getReturn(returnId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改退货单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.returnId != null) {
            updateReturn(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReturn(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const returnIds = row.returnId || this.ids;
      this.$modal.confirm('是否确认删除退货单编号为"' + returnIds + '"的数据项？').then(function () {
        return delReturn(returnIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 审核按钮操作 */
    handleAudit() {
      const returnId = this.ids[0];
      this.$modal.confirm('是否确认审核该退货单？').then(function () {
        return auditReturn(returnId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("审核成功");
      }).catch(() => { });
    },
    /** 执行退货按钮操作 */
    handleExecute() {
      const returnId = this.ids[0];
      this.$modal.confirm('是否确认执行退货？').then(function () {
        return executeReturn(returnId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("执行成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/purchase/return/export', {
        ...this.queryParams
      }, `return_${new Date().getTime()}.xlsx`)
    },
    /** 供应商变化处理 */
    handleSupplierChange(supplierId) {
      const supplier = this.supplierList.find(s => s.supplierId === supplierId);
      if (supplier) {
        this.form.supplierName = supplier.supplierName;
      }
    },
    /** 物料变化处理 */
    handleMaterialChange(index) {
      const material = this.materialList.find(m => m.materialId === this.form.returnItemList[index].materialId);
      if (material) {
        this.form.returnItemList[index].materialName = material.materialName;
        this.form.returnItemList[index].specification = material.specification;
        this.form.returnItemList[index].unitOfMeasure = material.unitOfMeasure;
      }
    },
    /** 添加退货明细 */
    addReturnItem() {
      this.form.returnItemList.push({
        materialId: null,
        materialName: null,
        specification: null,
        unitOfMeasure: null,
        quantity: 0,
        unitPrice: 0,
        amount: 0,
        batchNumber: null
      });
    },
    /** 删除退货明细 */
    removeReturnItem(index) {
      this.form.returnItemList.splice(index, 1);
    },
    /** 计算金额 */
    calculateAmount(index) {
      const item = this.form.returnItemList[index];
      item.amount = (item.quantity * item.unitPrice).toFixed(2);
    }
  }
};
</script>